// 二次封装 axios
import axios, { AxiosInstance, InternalAxiosRequestConfig } from "axios";

// 创建 axios 实例
const instance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
    // 设置 token
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code == 401) {
      // 登录失效，移除登录信息并跳转至 login
      localStorage.removeItem("token");
      localStorage.removeItem("username");
      window.location.href = "/#/login";
    }
    return res;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default instance;
